import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
public class Manager extends User{
    private List<Show> showList;
    private List<Hall> hallList;
    private List<Movie> movieList;
    private List<Order> orderList;
    private Scanner scanner = new Scanner(System.in);
    public Manager(String userId, String username, String password, String registerTime, String phone, String userType) {
        super(userId, username, password, registerTime, phone, userType);
        this.showList = new ArrayList<>();
        this.hallList = HallConfig.initHalls();
        this.movieList = Movie.getAllMovies();
        this.orderList = new ArrayList<>();
    }
    @Override
    public void login() {
        int chance = 3;
        int attempt = 0;
        while (attempt < chance) {
            System.out.print("请输入经理用户名：");
            String name = scanner.next();
            System.out.print("请输入密码：");
            String password = scanner.next();
            User user = null;
            for (User u : UserList.getAllUsers()) {
                if (u.getUserName().equals(name) && u.getUserType().equals("经理")) {
                    user = u;
                    break;
                }
            }
            if (user != null && user.getUserPassword().equals(password)) {
                Log.info(name, "登录系统", "经理登录成功");
                System.out.println("登录成功！欢迎您，" + user.getUserName() + "经理！");
                show(); // 进入经理菜单
                return;
            } else {
                attempt++;
                int remaining = chance - attempt;
                Log.warning(name, "登录系统", "经理登录失败，剩余" + remaining + "次机会");
                System.out.println("用户名/密码错误！剩余" + remaining + "次机会。");
            }
        }
        System.out.println("登录失败次数过多，退出登录。");
        Log.warning("未知用户", "登录系统", "经理登录失败次数超限");
    }

    @Override
    public void exit() {
        Log.info(getUserName(), "退出系统", "经理返回主菜单");
        System.out.println("已退出经理系统，返回主菜单");
    }

    @Override
    public void show() {
        while (true) {
            System.out.println("\n=======经理操作菜单=========");
            System.out.println("1------->影片管理");
            System.out.println("2------->排片管理");
            System.out.println("3------->查看销售数据");
            System.out.println("4------->重置前台密码");
            System.out.println("5------->修改自身密码");
            System.out.println("6------->退出");
            System.out.print("请输入1-6的数字选择功能：");
            int choice;
            try {
                choice = Integer.parseInt(scanner.next().trim());
            } catch (NumberFormatException e) {
                System.out.println("输入错误，请输入数字！");
                Log.error(getUserName(), "菜单选择", e);
                continue;
            }

            switch (choice) {
                case 1:
                    manageMovies();
                    break;
                case 2:
                    manageShows();
                    break;
                case 3:
                    viewSalesData();
                    break;
                case 4:
                    resetFrontDeskPassword();
                    break;
                case 5:
                    modifyPassword();
                    break;
                case 6:
                    exit();
                    return;
                default:
                    System.out.println("输入无效，请重新输入1-6的数字！");
            }
        }
    }
    public void manageMovies() {
        while (true) {
            System.out.println("\n=== 影片管理菜单 ===");
            System.out.println("1. 添加影片  2. 修改影片  3. 删除影片  4. 查询影片  5. 返回上一级");
            System.out.print("请输入1-5的整数选择功能：");
            int choice;
            try {
                choice = Integer.parseInt(scanner.next().trim());
            } catch (NumberFormatException e) {
                System.out.println("输入错误，请输入数字！");
                Log.error(getUserName(), "影片管理菜单选择", e);
                continue;
            }
            switch (choice) {
                case 1:
                    addMovie();
                    break;
                case 2:
                    modifyMovie();
                    break;
                case 3:
                    deleteMovie();
                    break;
                case 4:
                    searchMovie();
                    break;
                case 5:
                    return;
                default:
                    System.out.println("输入无效，请重新输入1-5的数字！");
            }
        }
    }

    public void manageShows() {
        while (true) {
            System.out.println("\n=== 排片管理菜单 ===");
            System.out.println("1. 增加场次  2. 修改场次  3. 删除场次  4. 自动排片  5. 返回上一级");
            System.out.print("请输入1-5的整数选择功能：");
            int choice;
            try {
                choice = Integer.parseInt(scanner.next().trim());
            } catch (NumberFormatException e) {
                System.out.println("输入错误，请输入数字！");
                Log.error(getUserName(), "排片管理菜单选择", e);
                continue;
            }
            switch (choice) {
                case 1:
                    addShow();
                    break;
                case 2:
                    modifyShow();
                    break;
                case 3:
                    deleteShow();
                    break;
                case 4:
                    autoArrangShow();
                    break;
                case 5:
                    return;
                default:
                    System.out.println("输入无效，请重新输入1-5的数字！");
            }
        }
    }

    private Hall findHallByName(String hallName) {
        for (Hall hall : this.hallList) {
            if (hall.getHallName().equals(hallName)) {
                return hall;
            }
        }
        return null;
    }

    private Movie findMovieByName(String movieName) {
        for (Movie movie : movieList) {
            if (movie.getName().equals(movieName)) {
                return movie;
            }
        }
        return null;
    }
    public void addShow() {
        System.out.println("\n=== 增加场次 ===");
        scanner.nextLine();
        System.out.print("请输入影片名称：");
        String movieName = scanner.nextLine().trim();
        Movie targetMovie = Movie.findMovie(movieName);
        if (targetMovie == null) {
            System.out.println("未找到该影片，请先在影片管理中添加");
            return;
        }
        System.out.println("可选放映厅：");
        for (Hall hall : hallList) {
            System.out.println("- " + hall.getHallName() + "（" + hall.getTotalRows() + "排，每排" + hall.getSeatsPerRow() + "座）");
        }
        System.out.print("请输入放映厅名称：");
        String hallName = scanner.nextLine().trim();
        Hall targetHall = HallConfig.getHallByName(hallList, hallName);
        if (targetHall == null) {
            System.out.println("放映厅名称错误");
            return;
        }
        System.out.print("请输入放映时间（格式：yyyy-MM-dd HH:mm）：");
        String timeStr = scanner.nextLine().trim();
        Date showTime;
        try {
            showTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(timeStr);
            long maxTime = new Date().getTime() + 7 * 24 * 60 * 60 * 1000L;
            if (showTime.getTime() > maxTime) {
                System.out.println("场次时间不能超过当前时间+7天");
                return;
            }
        } catch (ParseException e) {
            System.out.println("时间格式错误，请重新输入");
            Log.error(getUserName(), "添加场次-时间格式", e);
            return;
        }
        boolean hasConflict = false;
        for (Show existingShow : Show.getAllShows()) {
            if (existingShow.getHall().getHallName().equals(targetHall.getHallName()) && existingShow.isTimeConflict(new Show(null, targetMovie, targetHall, showTime, 0))) {
                hasConflict = true;
                break;
            }
        }
        if (hasConflict) {
            System.out.println("该放映厅在所选时间存在场次冲突，请重新选择时间");
            return;
        }
        System.out.print("请输入该场次票价：");
        double price;
        try {
            price = Double.parseDouble(scanner.nextLine().trim());
            if (price <= 0) {
                System.out.println("票价必须大于0");
                return;
            }
        } catch (NumberFormatException e) {
            System.out.println("票价输入错误");
            Log.error(getUserName(), "添加场次-票价格式", e);
            return;
        }
        String showId = "SHOW_" + UUID.randomUUID().toString().substring(0, 6);
        Show newShow = new Show(showId, targetMovie, targetHall, showTime, price);
        showList.add(newShow);
        Show.addToAllShows(newShow);
        targetHall.initSeatsForShow(showId);
        Log.info(getUserName(), "添加场次", "场次ID：" + showId + "，影片：" + movieName + "，影厅：" + hallName + "，时间：" + timeStr);
        System.out.println("场次添加成功！场次ID：" + showId);
    }
    private Show findShowById(String showId) {
        return showList.stream().filter(show -> show.getShowId().equals(showId)).findFirst().orElse(null);
    }


    private String getFieldName(String choice) {
        switch(choice) {
            case "1":
                return "影片名称";
            case "2":
                return "导演";
            case "3":
                return "主演";
            case "4":
                return "影片类型";
            case "5":
                return "剧情简介";
            case "6":
                return "时长";
            case "7":
                return "评分";
            case "8":
                return "上映状态";
            default:
                return "未知字段";
        }
    }
    public void modifyShow(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("\n=== 修改场次 ===");
        System.out.print("请输入要修改的场次ID：");
        String showId = scanner.nextLine().trim();
        Show targetShow = findShowById(showId);
        if (targetShow == null) {
            System.out.println("未找到该场次");
            return;
        }
        boolean hasSold = orderList.stream().flatMap(order -> order.getTickets().stream()).anyMatch(ticket -> ticket.getShowId().equals(showId) && ticket.getStatus() == 0);
        if (hasSold) {
            System.out.println("该场次已有售出票，不允许修改");
            return;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        System.out.println("当前场次信息：");
        System.out.println("影片：" + targetShow.getMovie().getName() + "，时间：" + sdf.format(targetShow.getShowTime()) + "，放映厅：" + targetShow.getHall().getHallName() + "，票价：" + targetShow.getPrice() + "元");
        System.out.print("请输入新影片名称（不修改请回车）：");
        String newMovieName = scanner.nextLine().trim();
        Movie newMovie = targetShow.getMovie();
        if (!newMovieName.isEmpty()) {
            newMovie = findMovieByName(newMovieName);
            if (newMovie == null) {
                System.out.println("未找到该影片，影片信息不修改");
                newMovie = targetShow.getMovie();
            }
        }
        System.out.print("请输入新票价（不修改请回车）：");
        String priceStr = scanner.nextLine().trim();
        double newPrice = targetShow.getPrice();
        if (!priceStr.isEmpty()) {
            try {
                newPrice = Double.parseDouble(priceStr);
                if (newPrice <= 0) {
                    System.out.println("票价必须为正数，票价不修改");
                    newPrice = targetShow.getPrice();
                }
            } catch (NumberFormatException e) {
                System.out.println("票价格式错误，票价不修改");
            }
        }
        System.out.print("请输入新放映时间（格式yyyy-MM-dd HH:mm，不修改请回车）：");
        String timeStr = scanner.nextLine().trim();
        Date newTime = targetShow.getShowTime();
        if (!timeStr.isEmpty()) {
            try {
                newTime = sdf.parse(timeStr);
                long maxTime = new Date().getTime() + 7 * 24 * 60 * 60 * 1000L;
                if (newTime.getTime() > maxTime) {
                    System.out.println("时间超出提前一周限制，时间不修改");
                    newTime = targetShow.getShowTime();
                }
            } catch (ParseException e) {
                System.out.println("时间格式错误，时间不修改");
            }
        }
        String oldMovieName = targetShow.getMovie().getName();
        targetShow.setMovie(newMovie);
        targetShow.setPrice(newPrice);
        targetShow.setShowTime(newTime);
        Log.info(getUserName(), "修改场次", String.format("时间=%s，原影片=%s，新影片=%s", sdf.format(newTime), oldMovieName, newMovie.getName()));
        System.out.println("场次修改成功");
    }
    public void deleteShow(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("\n=== 删除场次 ===");
        System.out.print("请输入要删除的场次ID：");
        String showId = scanner.nextLine().trim();

        Show targetShow = findShowById(showId);
        if (targetShow == null) {
            System.out.println("未找到该场次");
            return;
        }
        boolean hasSold = orderList.stream().flatMap(order -> order.getTickets().stream()).anyMatch(ticket -> ticket.getShowId().equals(showId) && ticket.getStatus() == 0);
        if (hasSold) {
            System.out.println("该场次已有售出票，不允许删除");
            return;
        }

        System.out.print("确认删除该场次？（y/n）：");
        String confirm = scanner.nextLine().trim();
        if (!"y".equalsIgnoreCase(confirm)) {
            System.out.println("已取消删除");
            return;
        }
        showList.remove(targetShow);
        Log.info(getUserName(), "删除场次", String.format("时间=%s，影片=%s", new SimpleDateFormat("yyyy-MM-dd HH:mm").format(targetShow.getShowTime()), targetShow.getMovie().getName()));
        System.out.println("场次删除成功");
    }
    public void autoArrangShow(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("\n=== 自动排片 ===");
        System.out.print("请输入排片天数（1-7天）：");
        int days;
        try {
            days = Integer.parseInt(scanner.nextLine().trim());
            if (days < 1 || days > 7) {
                System.out.println("天数必须在1-7之间，默认排7天");
                days = 7;
            }
        } catch (NumberFormatException e) {
            System.out.println("输入错误，默认排7天");
            days = 7;
        }
        List<Date> goldenTimes = generateGoldenTimes(days);
        List<Movie> sortedMovies = new ArrayList<>(movieList);
        sortedMovies.sort((m1, m2) -> Double.compare(m2.getScore(), m1.getScore()));
        int hallIndex = 0;
        int movieIndex = 0;
        for (Date time : goldenTimes) {
            Hall hall = hallList.get(hallIndex % hallList.size()); // 循环使用放映厅
            hallIndex++;
            Movie movie = sortedMovies.get(movieIndex % sortedMovies.size()); // 循环分配影片
            movieIndex++;
            boolean isConflict = showList.stream().anyMatch(show ->
                    show.getHall().getHallName().equals(hall.getHallName()) &&
                            show.getShowTime().equals(time));
            if (isConflict) {
                continue;
            }
            String showId = "SHOW_" + System.currentTimeMillis();
            Show newShow = new Show(showId, movie,hall,time,calculatePrice(movie, time));
            showList.add(newShow);
            hall.initSeatsForShow(showId);
        }
        System.out.println("自动排片完成，共生成" + goldenTimes.size() + "个场次");
        Log.info(getUserName(), "自动排片", String.format("完成排片: 天数=%d, 场次=%d, 操作时间=%s", days, goldenTimes.size(), new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date())));
        System.out.println("自动排片完成，共生成" + goldenTimes.size() + "个场次");
    }

    private Double calculatePrice(Movie movie, Date time) {
        double basePrice = 30.0;
        double scoreAdd = movie.getScore() * 2;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        double timeAdd = (hour >= 19 && hour <= 22) ? 20 : 0;
        double totalPrice = basePrice + scoreAdd + timeAdd;
        return Math.max(totalPrice, 10.0);
    }

    private List<Date> generateGoldenTimes(int days) {
        List<Date> goldenTimes = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (int i = 0; i < days; i++) {
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_YEAR, i);
            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            String timePattern;
            if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
                timePattern = "yyyy-MM-dd 19:00";
            } else {
                timePattern = "yyyy-MM-dd 20:00";
            }
            try {
                Date goldenTime = sdf.parse(sdf.format(calendar.getTime()).split(" ")[0] + " " + (timePattern.contains("19:00") ? "19:00" : "20:00"));
                if (goldenTime.after(new Date())) {
                    goldenTimes.add(goldenTime);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return goldenTimes;
    }

    public void viewSalesData() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("\n=== 销售数据查询 ===");
        System.out.println("1. 当日销售  2. 当周销售  3. 当月销售");
        System.out.print("请选择（1-3）：");
        int choice;
        try {
            choice = Integer.parseInt(scanner.nextLine().trim());
        } catch (NumberFormatException e) {
            System.out.println("输入错误");
            return;
        }

        Date now = new Date();
        long startTime = 0;
        String title = "";
        switch (choice) {
            case 1:
                startTime = getStartTimeOfDay(now);
                title = "当日";
                break;
            case 2:
                startTime = getStartTimeOfWeek(now);
                title = "当周";
                break;
            case 3:
                startTime = getStartTimeOfMonth(now);
                title = "当月";
                break;
            default:
                System.out.println("无效选择");
                return;
        }
        int totalTickets = 0;
        double totalAmount = 0.0;
        int refundTickets = 0;
        double refundAmount = 0.0;
        for (Order order : orderList) {
            if (order.getPayStatus() != 1) {
                continue;
            }
            if (order.getCreateTime().getTime() < startTime) {
                continue;
            }
            for (Ticket ticket : order.getTickets()) {
                if (ticket.getStatus() == 0) { // 正常票
                    totalTickets++;
                    totalAmount += ticket.getPrice();
                } else { // 已退票
                    refundTickets++;
                    refundAmount += ticket.getPrice();
                }
            }
        }

        System.out.println("\n=== " + title + "销售数据 ===");
        System.out.println("总售票数：" + totalTickets + "张");
        System.out.println("总销售额：" + totalAmount + "元");
        System.out.println("退票数：" + refundTickets + "张");
        System.out.println("退票金额：" + refundAmount + "元");
        System.out.println("实际销售额：" + (totalAmount - refundAmount) + "元");
    }
    private long getStartTimeOfMonth(Date now) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.set(Calendar.DAY_OF_MONTH, 1);  // 关键：定位到当月 1 日
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }
    private long getStartTimeOfDay(Date now) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }
    private long getStartTimeOfWeek(Date now) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }

    public void modifyPassword() {
        scanner.nextLine();
        System.out.print("请输入原密码：");
        String oldPwd = scanner.nextLine().trim();
        if (!oldPwd.equals(this.getUserPassword())) {
            System.out.println("原密码错误，修改失败");
            Log.warning(getUserName(), "修改自身密码", "原密码错误");
            return;
        }
        System.out.print("请输入新密码：");
        String newPwd = scanner.nextLine().trim();
        this.setUserPassword(oldPwd, newPwd);
        Log.info(getUserName(), "修改自身密码", "经理密码修改成功");
        System.out.println("密码修改成功");
    }

    public void resetFrontDeskPassword() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("\n=== 重置前台密码 ===");
        System.out.print("请输入要重置密码的前台用户名：");
        String username = scanner.nextLine().trim();
        User frontUser = null;
        for (User user : UserList.getAllUsers()) {
            if (user.getUserType().equals("前台") && user.getUserName().equals(username)) {
                frontUser = user;
                break;
            }
        }

        if (frontUser == null) {
            System.out.println("未找到该前台用户");
            return;
        }
        frontUser.setUserPassword("123456");
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
        Log.info(getUserName(), "重置密码", String.format("重置用户=%s, 时间=%s", username, time));
        System.out.println("密码已重置为123456，该用户登录时需修改密码");

    }
    public void addMovie() {
        System.out.println("\n===== 添加新影片 =====");
        scanner.nextLine();
        String name;
        while (true) {
            System.out.print("请输入影片名称：");
            name = scanner.nextLine().trim();
            if (name.isEmpty()) {
                System.out.println("影片名称不能为空，请重新输入！");
            } else if (Movie.isNameExists(name)) {
                System.out.println("该影片名称已存在，请更换名称！");
            } else {
                break;
            }
        }
        String director;
        while (true) {
            System.out.print("请输入导演：");
            director = scanner.nextLine().trim();
            if (director.isEmpty()) {
                System.out.println("导演不能为空，请重新输入！");
            } else {
                break;
            }
        }
        String actor;
        while (true) {
            System.out.print("请输入主演（多个用逗号分隔）：");
            actor = scanner.nextLine().trim();
            if (actor.isEmpty()) {
                System.out.println("主演不能为空，请重新输入！");
            } else {
                break;
            }
        }
        System.out.print("请输入影片类型（如：动作/喜剧/科幻）：");
        String type = scanner.nextLine().trim();
        if (type.isEmpty()) type = "未分类";
        System.out.print("请输入剧情简介：");
        String introduction = scanner.nextLine().trim();
        if (introduction.isEmpty()) introduction = "暂无简介";
        int duration = 0;
        while (true) {
            System.out.print("请输入影片时长（分钟）：");
            String durationInput = scanner.nextLine().trim();
            try {
                duration = Integer.parseInt(durationInput);
                if (duration <= 0) {
                    System.out.println("时长必须为正数，请重新输入！");
                } else {
                    break;
                }
            } catch (NumberFormatException e) {
                System.out.println("输入错误，请输入数字！");
                Log.error(getUserName(), "添加影片-时长输入", e);
            }
        }
        double score = 0;
        while (true) {
            System.out.print("请输入影片评分（0-10分）：");
            String scoreInput = scanner.nextLine().trim();
            try {
                score = Double.parseDouble(scoreInput);
                if (score < 0 || score > 10) {
                    System.out.println("评分必须在0-10分之间，请重新输入！");
                } else {
                    break;
                }
            } catch (NumberFormatException e) {
                System.out.println("输入错误，请输入数字！");
                Log.error(getUserName(), "添加影片-评分输入", e);
            }
        }
        Movie newMovie = new Movie(name, director, actor, introduction, duration, score, type);
        Movie.addToAllMovies(newMovie);
        Log.info(getUserName(), "添加影片", "影片名称：" + name + "，ID：" + newMovie.getMovieId());
        System.out.println("\n===== 影片添加成功！ =====");
        System.out.println("影片ID：" + newMovie.getMovieId());
        System.out.println("影片名称：" + newMovie.getName());
    }

    public void modifyMovie() {
        System.out.println("\n=== 修改影片 ===");
        if (movieList.isEmpty()) {
            System.out.println("当前无影片可修改");
            return;
        }
        System.out.println("当前影片列表：");
        for (Movie movie : movieList) {
            System.out.println("ID：" + movie.getMovieId() + " | 名称：" + movie.getName());
        }
        scanner.nextLine();
        System.out.print("请输入要修改的影片ID：");
        String movieId = scanner.nextLine().trim();
        Movie targetMovie = Movie.findMovie(movieId);

        if (targetMovie == null) {
            System.out.println("未找到ID为【" + movieId + "】的影片");
            return;
        }
        System.out.println("\n当前影片信息：");
        System.out.println(targetMovie.toString());
        System.out.println("\n可修改字段：");
        System.out.println("1. 影片名称  2. 导演  3. 主演  4. 简介  5. 时长(分钟)  6. 评分(0-10)  7. 类型  8. 上映状态");
        System.out.print("请输入要修改的字段编号（1-8）：");
        String choice;
        try {
            choice = scanner.nextLine().trim();
        } catch (Exception e) {
            System.out.println("输入错误");
            Log.error(getUserName(), "修改影片", e);
            return;
        }
        String logContent = "修改影片ID：" + movieId + "，";
        boolean modified = false;
        switch (choice) {
            case "1":
                System.out.print("请输入新的影片名称：");
                String newName = scanner.nextLine().trim();
                if (newName.isEmpty()) {
                    System.out.println("影片名称不能为空");
                    return;
                }
                if (Movie.isNameExists(newName) && !newName.equals(targetMovie.getName())) {
                    System.out.println("该影片名称已存在");
                    return;
                }
                logContent += "原名称：" + targetMovie.getName() + "，新名称：" + newName;
                targetMovie.setName(newName);
                modified = true;break;

            case "2":
                System.out.print("请输入新的导演：");
                String newDirector = scanner.nextLine().trim();
                if (newDirector.isEmpty()) {
                    System.out.println("导演不能为空");
                    return;
                }
                logContent += "原导演：" + targetMovie.getDirector() + "，新导演：" + newDirector;
                targetMovie.setDirector(newDirector);
                modified = true;
                break;
            case "3":
                System.out.print("请输入新的主演：");
                String newActor = scanner.nextLine().trim();
                if (newActor.isEmpty()) {
                    System.out.println("主演不能为空");
                    return;
                }
                logContent += "原主演：" + targetMovie.getActor() + "，新主演：" + newActor;
                targetMovie.setActor(newActor);
                modified = true;
                break;
            case "4":
                System.out.print("请输入新的简介：");
                String newIntro = scanner.nextLine().trim();
                logContent += "简介已更新";
                targetMovie.setIntroduction(newIntro);
                modified = true;
                break;
            case "5":
                System.out.print("请输入新的时长（分钟）：");
                try {
                    int newDuration = Integer.parseInt(scanner.nextLine().trim());
                    if (newDuration <= 0) {
                        System.out.println("时长必须大于0");
                        return;
                    }
                    logContent += "原时长：" + targetMovie.getDuration() + "，新时长：" + newDuration;
                    targetMovie.setDuration(newDuration);
                    modified = true;
                } catch (NumberFormatException e) {
                    System.out.println("时长必须是数字");
                    Log.error(getUserName(), "修改影片时长", e);
                    return;
                }
                break;
            case "6":
                System.out.print("请输入新的评分（0-10）：");
                try {
                    double newScore = Double.parseDouble(scanner.nextLine().trim());
                    targetMovie.setScore(newScore); // Movie类已包含0-10校验
                    if (newScore == targetMovie.getScore()) { // 校验是否成功设置
                        logContent += "原评分：" + targetMovie.getScore() + "，新评分：" + newScore;
                        modified = true;
                    }
                } catch (NumberFormatException e) {
                    System.out.println("评分必须是数字");
                    Log.error(getUserName(), "修改影片评分", e);
                    return;
                }
                break;
            case "7":
                System.out.print("请输入新的类型：");
                String newType = scanner.nextLine().trim();
                if (newType.isEmpty()) {
                    System.out.println("类型不能为空");
                    return;
                }
                logContent += "原类型：" + targetMovie.getType() + "，新类型：" + newType;
                targetMovie.setType(newType);
                modified = true;
                break;
            case "8":
                System.out.print("请设置上映状态（1=上映，0=下架）：");
                String statusInput = scanner.nextLine().trim();
                if ("1".equals(statusInput)) {
                    targetMovie.setShowing(true);
                    logContent += "状态改为：已上映";
                    modified = true;
                } else if ("0".equals(statusInput)) {
                    targetMovie.setShowing(false);
                    logContent += "状态改为：未上映";
                    modified = true;
                } else {
                    System.out.println("输入无效，只能输入1或0");
                    return;
                }
                break;
            default:
                System.out.println("无效的字段编号");
                return;
        }
        if (modified) {
            Log.info(getUserName(), "修改影片", logContent);
            System.out.println("影片信息修改成功！");
            System.out.println("修改后信息：");
            System.out.println(targetMovie.toString());
        } else {
            System.out.println("未修改任何信息");
        }
    }
    public void deleteMovie(){
        Scanner reader = new Scanner(System.in);
        System.out.print("请输入要删除的电影ID或名称：");
        String key = reader.nextLine();
        Movie target = Movie.findMovie(key);
        if (target == null) {
            System.out.println("未找到该电影！");
            return;
        }
        System.out.println("确定要删除电影吗（y/n）");
        if(reader.next().equals("y")){
            Movie.removeFromAllMovies(target);
            Log.info(getUserName(), "删除影片", "影片名称：" + target.getName() + "，ID：" + target.getMovieId());
            System.out.println("电影删除成功！");
        }else{
            System.out.println("已取消删除该电影");
        }
    }
    public void searchMovie(){
        System.out.println("所有电影列表：");
        for (Movie movie : Movie.getAllMovies()) {
            System.out.println("\n---------------------");
            System.out.println(movie.toString());
        }
    }
}
